# coding=utf-8
"""
Python FTP 操作
from ftplib import FTP      # 加载ftp模块
ftp = FTP()                 # 获取FTP对象
ftp.set_debuglevel(2)       # 打开调试级别2，显示详细信息
ftp.connect('IP', PORT) # 连接ftp，server和端口
ftp.login('user', 'password')  # 登录用户
print(ftp.getwelcome())     # 打印欢迎信息
ftp.cmd('xxx/xxx')          # 进入远程目录
ftp.quit                    # 退出ftp
ftp相关的命令操作
ftp.cwd(pathname)           # 设置FTP当前操作的路径
ftp.dir()                   # 显示目录下所有目录的信息
ftp.nlst()                  # 获取目录下的文件
ftp.mkd(pathname)           # 新建远程目录
ftp.rmd(dirname)            # 删除远程目录
ftp.pwd()                   # 返回当前所在位置
ftp.delete(filename)        # 删除远程文件
ftp.rename(fromname, toname)    #将fromname改为toname
ftp.storbinaly('STOR filename.txt',file_handel,bufsize)  # 上传目标文件
ftp.retrbinary('RETR filename.txt',file_handel,bufsize)  # 下载FTP文件
"""
import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s line:%(lineno)d %(levelname)s:%(message)s',
                    datefmt='%H:%M:%S',
                    )
import os
from ftplib import FTP
from queue import Queue
from threading import Thread



class FtpClicent():
    def __init__(self, host, port, user="", pwd=""):
        self.ftp = FTP()
        self.login(host, port, user, pwd)
        #远程目录列表
        self.exists = set()

    def login(self, host, port, user, passwd):
        logging.info("开始连接...")
        self.ftp.connect(host, port)
        logging.info("连接成功")
        self.ftp.login(user, passwd)
        logging.info("登录成功")
        self.ftp.encoding = 'utf-8'

    def downloadfile(self, remotepath, localpath=None):
        """ 下载文件 """
        bufsize = 1024
        if not localpath:
            localpath = os.path.basename(remotepath)
        with open(localpath, 'wb') as fp:
            cmd = f"RETR {remotepath}"
            self.ftp.retrbinary(cmd, fp.write, bufsize)
        logging.info(f'文件 {remotepath} 下载成功！')


    def dld_path(self, remote_path, local_path):
        os.makedirs(local_path, exist_ok=True)
        file_list = []
        self.ftp.retrlines(f'LIST {remote_path}', file_list.append)
        i = 0
        for file_info in file_list:
            i += 1
            print(i, len(file_list))
            file_name = file_info.split(":", 1)[-1].split(" ", 1)[-1]
            logging.info(file_info)
            _remote_path = f"{remote_path}/{file_name}"
            _local_path = os.path.join(local_path, file_name)
            if file_info[0] == "d":
                self.dld_dir(_remote_path, _local_path)
            else:
                self.downloadfile(_remote_path, _local_path)
                




def to_phone():
    ftp = FtpClicent()
    list = []
    for root, dirs, files in os.walk(dst, topdown=False):
        for name in files:
            list.append(os.path.join(root, name))
    phone_list = ftp.get_file_list("music")
    for i in list:
        dst_file = i.replace(dst,"")
        dst_file = dst_file.replace("\\","/")
        #print(dst_file)
        if dst_file in phone_list:
            continue
        print(i)
        ftp.uploadfile(i,dst_file)



ftp = FtpClicent("192.168.123.198", 3721)
ttt = ".989b758c89cf66cfe6463de6be69059d"
ftp.dld_path("Download/browser/视频/%s" % ttt, "d:\\111\\ddd\\xxx2\\%s" % ttt)




